<template>
  <view class="page">
    <!-- 顶部导航栏 -->
    <view class="tabs">
      <view 
        class="tab-item" 
        :class="{active: currentTab === 'ALL'}" 
        @tap="switchTab('ALL')"
      >
        <text>全部订单</text>
      </view>
      <view 
        class="tab-item" 
        :class="{active: currentTab === 'PENDING'}" 
        @tap="switchTab('PENDING')"
      >
        <text>待接单</text>
      </view>
      <!-- 去除重复的待支付标签，统一在“全部订单”中以按钮形式体现 -->
      <view 
        class="tab-item" 
        :class="{active: currentTab === 'IN_PROGRESS'}" 
        @tap="switchTab('IN_PROGRESS')"
      >
        <text>进行中</text>
      </view>
      <view 
        class="tab-item" 
        :class="{active: currentTab === 'COMPLETED'}" 
        @tap="switchTab('COMPLETED')"
      >
        <text>已完成</text>
      </view>
      <view 
        class="tab-item" 
        :class="{active: currentTab === 'CANCELLED'}" 
        @tap="switchTab('CANCELLED')"
      >
        <text>已取消</text>
      </view>
      <view 
        class="tab-item" 
        :class="{active: currentTab === 'SHOP'}" 
        @tap="switchTab('SHOP')"
      >
        <text>商品订单</text>
      </view>
    </view>
    
    <!-- 订单列表 -->
    <view class="card" v-for="(order, index) in filteredOrders" :key="index">
      <view class="row">
        <view class="left">
          <image class="avatar" src="/static/project/2025-10-14_110352_756.png" mode="aspectFill"/>
          <view class="info">
            <text class="title">{{ currentTab==='SHOP' ? '积分商品订单' : '陪爬预约' }}</text>
            <text class="sub" v-if="currentTab!=='SHOP'">{{order.serviceDate}} {{order.startTime}}-{{order.endTime}}</text>
            <text class="sub" v-else>订单号：{{order.orderNo}}</text>
          </view>
        </view>
        <view class="badge">{{getStatusText(order)}}</view>
      </view>
      <view class="row2">
        <text class="price">{{ currentTab==='SHOP' ? (order.amount + ' 积分') : ('¥' + order.amount) }}</text>
        <view class="actions">
          <button v-if="currentTab!=='SHOP' && showPayButton(order)" class="btn pay" size="mini" @tap.stop="handlePay(order)">去支付</button>
          <button v-if="showTrackButton(order)" class="btn track" size="mini" @tap.stop="handleTrack(order)">进度跟踪</button>
          <button v-if="currentTab!=='SHOP' && showDetailButton(order)" class="btn detail" size="mini" @tap.stop="handleDetail(order)">查看详情</button>
          <button v-if="currentTab==='SHOP'" class="btn detail" size="mini" @tap.stop="goShopDetail(order)">查看详情</button>
          <!-- 已完成订单：在查看详情旁显示 去评价/已评价 -->
          <button v-if="order.orderStatus === 'COMPLETED' && !order.hasFeedback" class="btn rate" size="mini" @tap.stop="handleRate(order)">去评价</button>
          <button v-if="order.orderStatus === 'COMPLETED' && order.hasFeedback" class="btn rated" size="mini" disabled>已评价</button>
          <button v-if="showCancelButton(order)" class="btn cancel" size="mini" @tap.stop="handleCancel(order)">取消订单</button>
        </view>
      </view>
    </view>
    <view v-if="filteredOrders.length === 0" class="empty">暂无订单</view>
    <emergency-sos bottom="160" right="24" />
    <custom-tabbar :active="3" />
  </view>
</template>

<script>
import CustomTabbar from '@/components/custom-tabbar/custom-tabbar.vue'
import EmergencySOS from '@/components/emergency-sos/emergency-sos.vue'
import { listOrders, cancelOrder } from '@/api/order'
import { getFeedbackByOrder } from '@/api/feedback'
import store from '@/store'
export default {
  components: { CustomTabbar, EmergencySOS },
  data(){
    return { 
      orders: [], 
      loading: false,
      currentTab: 'ALL', // ALL, PENDING, IN_PROGRESS, COMPLETED, CANCELLED, SHOP
      shopOrders: []
    }
  },
  computed: {
    // 根据当前选中的标签过滤订单
    filteredOrders() {
      if (this.currentTab === 'SHOP') {
        return this.shopOrders
      } else if (this.currentTab === 'ALL') {
        return this.orders
      } else if (this.currentTab === 'UNPAID') {
        // 待支付：订单状态为已确认且支付状态为未支付
        return this.orders.filter(o => o.orderStatus === 'CONFIRMED' && o.paymentStatus === 'UNPAID')
      } else if (this.currentTab === 'IN_PROGRESS') {
        // 进行中：订单状态为进行中 或者 (已确认且已支付)
        return this.orders.filter(o => 
          o.orderStatus === 'IN_PROGRESS' || 
          (o.orderStatus === 'CONFIRMED' && o.paymentStatus === 'PAID')
        )
      } else {
        // 其他状态按订单状态过滤
        return this.orders.filter(o => o.orderStatus === this.currentTab)
      }
    }
  },
  onShow(){ 
    console.log('页面显示，开始获取订单')
    this.fetch()
    this.fetchShopOrders()
  },
  methods: {
    // 切换标签
    switchTab(tab) {
      this.currentTab = tab
      console.log('切换到标签:', tab, '过滤后订单数:', this.filteredOrders.length)
    },
    async fetch(){
      this.loading = true
      try{
        const uid = store.getters && store.getters.id
        console.log('当前用户ID:', uid)
        
        const res = await listOrders({ userId: uid })
        console.log('订单列表响应:', res)
        
        // 处理返回的数据
        if (res && res.code === 200 && res.data) {
          const list = Array.isArray(res.data) ? res.data : []
          console.log('订单列表:', list, '长度:', list.length)
          
          // 重新赋值整个数组，确保响应式更新
          const newOrders = list.map(it=>({
            id: it.id,
            orderNo: it.orderNo,
            serviceDate: it.serviceDate,
            startTime: it.startTime,
            endTime: it.endTime,
            amount: it.amount,
            orderStatus: it.orderStatus,
            paymentStatus: it.paymentStatus || 'UNPAID'
          }))
          
          console.log('处理后的订单:', newOrders, '长度:', newOrders.length)
          
          // 使用 $set 确保响应式更新
          this.$set(this, 'orders', newOrders)

          // 标记已完成订单是否已评价
          await this.markFeedbackFlags()
          
          console.log('赋值后 this.orders:', this.orders, '长度:', this.orders.length)
        } else {
          console.error('获取订单失败:', res.msg)
          this.orders = []
        }
      } catch(error) {
        console.error('获取订单异常:', error)
        this.orders = []
      } finally { 
        this.loading = false 
      }
    },
    async fetchShopOrders(){
      try{
        const api = require('@/api/goods')
        const r = await api.listShopOrders({})
        const list = (r && r.data) || []
        this.shopOrders = Array.isArray(list) ? list.map(it => ({
          id: it.id,
          orderNo: it.orderNo,
          amount: Number(it.totalPoints || 0),
          status: it.status,
          createTime: it.createTime
        })) : []
      }catch(e){ this.shopOrders = [] }
    },
    // 标记每个已完成订单的评价状态
    async markFeedbackFlags(){
      const completed = (this.orders || []).filter(o => o.orderStatus === 'COMPLETED')
      if (!completed.length) return
      try{
        await Promise.all(completed.map(async (o) => {
          try{
            const r = await getFeedbackByOrder(o.id)
            const has = !!(r && r.data && r.data.id)
            this.$set(o, 'hasFeedback', has)
          }catch(e){ this.$set(o, 'hasFeedback', false) }
        }))
        this.$forceUpdate()
      }catch(e){}
    },
    
    // 获取状态文本（考虑支付状态）
    getStatusText(o){
      if (o.orderStatus === 'PENDING') return '待接单'
      if (o.orderStatus === 'CONFIRMED') {
        // 已接单但未支付
        if (o.paymentStatus === 'UNPAID') return '已确认'
        // 已接单且已支付
        return '已支付'
      }
      if (o.orderStatus === 'IN_PROGRESS') return '进行中'
      if (o.orderStatus === 'COMPLETED') return '已完成'
      if (o.orderStatus === 'CANCELLED') return '已取消'
      return o.orderStatus
    },
    
    // 获取状态标签样式
    getBadgeClass(o){
      if (o.orderStatus === 'PENDING') return 'badge-pending'
      if (o.orderStatus === 'CONFIRMED') {
        return o.paymentStatus === 'PAID' ? 'badge-paid' : 'badge-confirmed'
      }
      if (o.orderStatus === 'IN_PROGRESS') return 'badge-progress'
      if (o.orderStatus === 'COMPLETED') return 'badge-completed'
      if (o.orderStatus === 'CANCELLED') return 'badge-cancelled'
      return ''
    },
    
    // 是否显示"去支付"按钮
    showPayButton(o){
      return o.orderStatus === 'CONFIRMED' && o.paymentStatus === 'UNPAID'
    },
    
    // 是否显示"进度跟踪"按钮
    showTrackButton(o){
      // 已支付或进行中的订单显示进度跟踪
      return (o.orderStatus === 'CONFIRMED' && o.paymentStatus === 'PAID') || 
             o.orderStatus === 'IN_PROGRESS'
    },
    
    // 是否显示"查看详情"按钮
    showDetailButton(o){
      // 已支付或进行中的订单显示查看详情
      return (o.orderStatus === 'CONFIRMED' && o.paymentStatus === 'PAID') || 
             o.orderStatus === 'IN_PROGRESS' || 
             o.orderStatus === 'COMPLETED'
    },
    
    // 是否显示"取消订单"按钮
    showCancelButton(o){
      // 未取消且未完成的订单可以取消
      // 已支付的订单不能取消（根据业务需求调整）
      return o.orderStatus !== 'CANCELLED' && 
             o.orderStatus !== 'COMPLETED' &&
             !(o.orderStatus === 'CONFIRMED' && o.paymentStatus === 'PAID')
    },
    
    // 处理卡片点击
    handleCardClick(order){
      this.goDetail(order)
    },
    
    // 处理去支付按钮点击
    handlePay(order){
      this.goPay(order)
    },
    
    // 处理进度跟踪按钮点击
    handleTrack(order){
      this.goTrack(order)
    },
    
    // 处理查看详情按钮点击
    handleDetail(order){
      this.goDetail(order)
    },
    // 去评价
    handleRate(order){
      this.goRate(order)
    },
    
    // 处理取消订单按钮点击
    handleCancel(order){
      this.onCancel(order)
    },
    
    goDetail(o){
      uni.navigateTo({ url: `/pages/order/detail?id=${o.id}` })
    },
    goTrack(o){
      // 显示订单进度跟踪弹窗
      let progressText = ''
      if (o.orderStatus === 'CONFIRMED' && o.paymentStatus === 'PAID') {
        progressText = '✅ 订单已支付\n⏳ 等待配爬员开始服务\n\n配爬员将在约定时间前联系您，请保持手机畅通。'
      } else if (o.orderStatus === 'IN_PROGRESS') {
        progressText = '✅ 订单已支付\n✅ 配爬员已开始服务\n⏳ 服务进行中\n\n祝您旅途愉快！如有问题请及时联系配爬员。'
      } else {
        progressText = '当前订单状态：' + this.getStatusText(o)
      }
      
      uni.showModal({
        title: '订单进度',
        content: progressText,
        showCancel: false,
        confirmText: '我知道了'
      })
    },
    goPay(o){
      // 跳转到正式支付页面（系统导航返回可回到列表）
      uni.navigateTo({ url: `/pages/order/pay?id=${o.id}` })
    },
    goRate(o){
      uni.navigateTo({ url: `/pages/order/rate?orderId=${o.id}` })
    },
    async onCancel(o){
      if (!o || !o.id) return
      // 询问并输入取消原因（支持 editable，低版本降级为默认原因）
      uni.showModal({
        title: '取消订单',
        content: '请输入取消原因',
        editable: true,
        placeholderText: '如：行程变更',
        confirmText: '确定取消',
        success: async (res) => {
          if (!res.confirm) return
          const reason = (res.content && String(res.content).trim()) || '用户主动取消'
          try{
            const r = await cancelOrder(o.id, reason)
            if ((r && r.code) === 200) {
              this.$modal && this.$modal.showToast('已取消订单')
              this.fetch()
            }
          }catch(e){}
        }
      })
    },
    goShopDetail(o){
      uni.navigateTo({ url: `/pages/shop/order-detail?id=${o.id}` })
    }
  }
}
</script>

<style scoped>
.page { 
  padding: 0 0 120rpx 0; 
  background: #f7fafc; 
  min-height: 100vh;
}

/* 顶部导航栏 */
.tabs {
  display: flex;
  background: #fff;
  padding: 0 12rpx;
  position: sticky;
  top: 0;
  z-index: 10;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}
.tab-item {
  flex: 1;
  text-align: center;
  padding: 24rpx 0;
  font-size: 28rpx;
  color: #666;
  position: relative;
  transition: all 0.3s;
}
.tab-item.active {
  color: #1890ff;
  font-weight: 600;
}
.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 48rpx;
  height: 6rpx;
  background: #1890ff;
  border-radius: 3rpx;
}
.card { 
  background: #fff; 
  border-radius: 16rpx; 
  padding: 24rpx; 
  margin: 20rpx 12rpx; 
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,.08); 
}
.row { 
  display: flex; 
  align-items: center; 
  justify-content: space-between; 
}
.left { 
  display: flex; 
  align-items: center; 
  flex: 1;
}
.avatar { 
  width: 80rpx; 
  height: 80rpx; 
  border-radius: 50%; 
  background: #f3f4f6; 
  flex-shrink: 0;
}
.info { 
  margin-left: 20rpx; 
  flex: 1;
}
.title { 
  display: block; 
  font-size: 28rpx;
  font-weight: 700; 
  color: #333;
  margin-bottom: 8rpx;
}
.sub { 
  display: block; 
  color: #999; 
  font-size: 24rpx; 
}
.badge { 
  padding: 8rpx 16rpx; 
  border-radius: 8rpx; 
  font-size: 24rpx; 
  background: #f0f0f0;
  color: #666;
  flex-shrink: 0;
  margin-left: 12rpx;
}
.row2 { 
  margin-top: 20rpx; 
  display: flex; 
  align-items: center; 
  justify-content: space-between; 
  padding-top: 20rpx;
  border-top: 1rpx solid #f0f0f0;
}
.price { 
  color: #ff6b6b; 
  font-weight: 700; 
  font-size: 32rpx;
}
.actions { 
  display: flex; 
}
.btn { 
  margin-left: 12rpx;
  padding: 0 24rpx;
  height: 56rpx;
  line-height: 56rpx;
  font-size: 24rpx;
  border-radius: 8rpx;
}
.btn.pay { 
  background: #07c160; 
  color: #fff; 
}
.btn.track { 
  background: #ff9500; 
  color: #fff; 
}
.btn.detail { 
  background: #576b95; 
  color: #fff; 
}
.btn.rate {
  background: #1989fa;
  color: #fff;
}
.btn.rated {
  background: #e5e7eb;
  color: #666;
}
.btn.cancel { 
  background: #fff; 
  color: #999; 
  border: 1rpx solid #e5e5e5; 
}
.empty { 
  text-align: center; 
  color: #999; 
  padding: 80rpx 0; 
  font-size: 28rpx;
}
</style>


